// import logo from './logo.svg';
// import './App.css';
// import Clock from './components/Clock/Clock';
// import Swiper from './components/Swipper/Swipper';
// import Todo from './components/Todo/TodoList/TodoList';
//导入相关组件
// import { NavLink, useRoutes } from 'react-router-dom';
// import routesArr from './routes';
import Home from './pages/Home/Home'
import About from './pages/About/About'
import { createContext, useContext, useEffect, useState } from 'react';

function App() {
  return <div>
    <BrowserRouter>
      <Link to="/home">Home</Link>
      <Link to="/about">About</Link>
      <Route path="/home" element={<Home />} />
      <Route path="/about" element={<About />} />
    </BrowserRouter>
  </div>
}

//声明一个 context 对象
let context = createContext();

//自定义 HashRouter
function BrowserRouter(props) {
  //声明一个状态
  let [pathname, setPathname] = useState(window.location.pathname); //  /home
  useEffect(() => {
    // 全局事件 popstate   属于 window 对象
    window.addEventListener('popstate', () => {
      //重新渲染组件, 更新状态
      setPathname(window.location.pathname);
    });
  }, [])

  return <context.Provider value={[pathname, setPathname]}>{props.children}</context.Provider>;
}

//Link 组件
function Link(props) {
  //获取context的值
  let [pathname, setPathname] = useContext(context);

  return <a href={props.to} onClick={(e) => {
    //阻止默认行为
    e.preventDefault();
    //调用 history.pushState 向历史栈结构中压入记录
    window.history.pushState(null, null, props.to);
    //更新 pathname 状态,重新渲染组件
    setPathname(props.to);
  }}>{props.children}</a>
}
//自定义 Route 组件
function Route(props) {
  //根据当前页面的 hash 值 决定对应的组件是否被渲染
  let [pathname] = useContext(context);
  let path = props.path;
  //判断
  if (pathname === path) {
    return props.element;
  } else {
    return null;
  }
}

export default App;
